﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExpenseSystem.Model;
using ExpenseSystem.Fether;
using ExpenseSystem.DataUpdater;
using ExpenseSystem.Common;
using ExpenseSystem.Core.Authority;
using ExpenseSystem.DataUpdater.Validation;

namespace ExpenseSystem.Core.SalesPointModules
{
    public class RegionUpdaterRegister
    {
        int rows;
        UserProfile userProfile;
        public RegionUpdaterRegister()
        {
            userProfile = Authority.Authority.GetUserProfile();
        }
        public NormalDataUpdater<RegionModel> GetRegionUpdater()
        {
            NormalDataUpdater<RegionModel> systemDataUpdater = new NormalDataUpdater<RegionModel>();
            systemDataUpdater.DataUpdating += DataNotSpaceValid;
            systemDataUpdater.DataUpdating += SingletonValid;
            systemDataUpdater.DataDeleting += CheckAvaliable;
            return systemDataUpdater;
        }
        private void CheckAvaliable(object sender, DataValidationEventArgs<RegionModel> e)
        {
            string message;
            CustomerFetcher customerFetcher = new CustomerFetcher();
            SalesPointFetcher salesPointFetcher = new SalesPointFetcher();
            if(customerFetcher.ListByRegion(e.Delete.Site, e.Delete.AutoId,out message, out rows).Count>0)
            {
                e.Cancle = true;
                message = String.Format("代号[{0}]已被客户信息占用", e.Delete.Code);
                return;
            }
            if (salesPointFetcher.ListByRegion(e.Delete.Site, e.Delete.AutoId, out message, out rows).Count > 0)
            {
                e.Cancle = true;
                message = String.Format("代号[{0}]已被门店信息占用", e.Delete.Code);
                return;
            }
        }
        private void SingletonValid(object sender, DataValidationEventArgs<RegionModel> e)
        {
            RegionFetcher RegionFetcher = new RegionFetcher();
            string message = "";
             
            RegionModel Region = RegionFetcher.GetByCode(userProfile.SiteId,e.Insert.Code,  out message);
            if (Region != null && Region.AutoId != e.Insert.AutoId)
            {
                e.Cancle = true;
                message = String.Format("代号[{0}]已被[{1}]占用", Region.Code, Region.Name);
                return;
            }
        }

        private void DataNotSpaceValid(object sender, DataValidationEventArgs<RegionModel> e)
        {
            if (String.IsNullOrWhiteSpace(e.Insert.Code))
            {
                e.Message = "代号不能为空";
                e.Cancle = true;
                return;
            }
            if (String.IsNullOrWhiteSpace(e.Insert.Name))
            {
                e.Message = "名称不能为空";
                e.Cancle = true;
                return;
            }
        }
    }
}
